#include "TCPTransport.h"
#include "MsnConnection.h"
#include "MsnCommand.h"
#include "Util.h"


TCPTransport::TCPTransport()
{

}

TCPTransport::~TCPTransport()
{
	DEBUG(_T("~TCPTransport"));
}

void* TCPTransport::Entry()
{
    DEBUG(_T("TCPTransport thread start: ") + wxString::Format(_T("%d"),this->GetId()));

	//open socket
    connected = this->Open();

	//try once more
/*
	if(!connected && !retryServerAddress.IsEmpty()){
		connected =this->Open(retryServerAddress, serverPort);
	}
*/

	if(!connected){
        return 0;
	}

    while (!closed && !TestDestroy()){
		//there're some % characters which may lead to ST_INVALID assert failure in DEBUG mode
        wxString cmdLine = ReadLine();

		if(closed || TestDestroy()){
            DEBUG(_T("transport closed"));

			if(connection){
				connection->ConnectionClosed();
			}
            break;
        }

        if(socket->LastCount() > 0){
            DEBUG(_T("<<<") + cmdLine);
            //m_LastActive = wxDateTime::GetTimeNow();

            //connection->ProcessCommand(line);

			MsnCommand* cmd = MsnCommandFactory::Get().CreateCommand(cmdLine);

			MsnCommandWrapper wrapper(cmd);	

			if(wrapper.IsPayloadCommand()){
				this->ReadData(wrapper.GetPayloadBuffer(), wrapper.GetPayloadLength());
			}

			connection->ProcessCommand(&wrapper);

        }

        if(socket->Error()){
			DEBUG(wxString::Format(_T("socket error occured: %d "), socket->LastError()));
            connection->ConnectionBroken();
            break;
        }
    }

    DEBUG(_T("TCPTransport thread exit:")+ wxString::Format(_T("%d"), this->GetId()));
    return 0;
}

void TCPTransport::SendData(void* data, unsigned int size)
{
	socket->Write(data, size);
}

